package org.example.bio;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpHandler {

  private static final Logger logger = LoggerFactory.getLogger(HttpHandler.class);

  private final Socket socket;

  public HttpHandler(Socket socket) {
    this.socket = socket;
  }

  private String calcHttpPayload() throws IOException {
    StringBuilder httpPayload = new StringBuilder();
    InputStreamReader isr = new InputStreamReader(socket.getInputStream());
    char[] charBuf = new char[1024];
    int mark = -1;
    while ((mark = isr.read(charBuf)) != -1) {
      httpPayload.append(charBuf, 0, mark);
      if (mark < charBuf.length) {
        break;
      }
    }
    return httpPayload.toString();
  }

  public void handler() {
    try {
      logger.debug("----------------------- start -------------------------------------");
      while (true) {
        String httpPayload = calcHttpPayload();
        logger.debug(httpPayload);

        socket.getOutputStream().
            write("""
                HTTP/1.1 200 OK\r
                Content-Type: text/html; charset=utf-8\r
                \r
                <h1>哈哈哈哈</h1>\r
                """.getBytes());
        socket.getOutputStream().flush();
      }
    }
    catch (Exception e) {
      System.out.println(e.getMessage());
      logger.debug("----------------------- end -------------------------------------");
    }
  }
}
